﻿/***************************************************************
 * 开发人员：网魂小兵@http://www.mozlite.com
 * 
 * 目标标本：4.0.30319.239
 * 
 * 最后修改：2011/11/10 16:08:19
 * ************************************************************/
namespace Mozlite.Common
{
    using System;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Collections.Generic;

    /// <summary>
    /// 自动登录的Cookie类。
    /// </summary>
    public class AutoLoginCookie
    {
        static AutoLoginCookie()
        {
            cookieName = "AutoLoginCookie";
        }

        private HttpContext context;
        private static readonly string cookieName;
        private HttpCookie theCookie;
        /// <summary>
        /// 初始化<see cref="T:Mozlite.Common.AutoLoginCookie"/>类。
        /// </summary>
        public AutoLoginCookie()
        {
            DefaultCookieValue = true;
            this.context = HttpContext.Current;
            this.theCookie = this.context.Request.Cookies[cookieName];
            if (this.theCookie == null)
            {
                this.theCookie = new HttpCookie(cookieName);
            }
            else
            {
                this.theCookie = this.context.Request.Cookies[cookieName];
            }
        }
        /// <summary>
        /// 获取自动登录Cookie值。
        /// </summary>
        /// <returns>返回自动登录Cookie值。</returns>
        public bool GetValue()
        {
            try
            {
                return Convert.ToBoolean(this.theCookie.Value.Trim());
            }
            catch
            {
                return this.DefaultCookieValue;
            }
        }
        /// <summary>
        /// 写入是否自动登录Cookie。
        /// </summary>
        /// <param name="autoLogin">是否自动登录。</param>
        /// <returns>返回是否写入Cookie。</returns>
        public bool Write(bool autoLogin)
        {
            if (this.theCookie == null)
            {
                return false;
            }
            this.theCookie.Value = autoLogin.ToString();
            this.theCookie.Expires = DateTime.Now.AddYears(1);
            this.context.Response.Cookies.Add(this.theCookie);
            return true;
        }
        /// <summary>
        /// 获取或设置默认Cookie值。
        /// </summary>
        public bool DefaultCookieValue { get; set; }
        /// <summary>
        /// 获取Cookie中是否有值，或是否有Cookie。
        /// </summary>
        public bool HasValue
        {
            get
            {
                return !string.IsNullOrEmpty(this.theCookie.Value);
            }
        }
    }
}